<template>
  <div>
    <el-dialog
      title="已创建序列号"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      width="900px"
      :before-close="cancel">
      <el-row class="mb8">
        <el-col :span="4">
          sku:<span style="font-weight: bold">{{ detail.skuNo }} </span>
        </el-col>
        <el-col :span="4">
          库位号:<span style="font-weight: bold">
            {{ detail.positionNo }}
          </span>
        </el-col>
      </el-row>
      <el-row class="mb8">
        <el-col :span="4">
          <!-- 0-否 1-是 -->
          是否会过期:
          <span v-if="detail.isExpired == 1" style="font-weight: bold; color: red"> 是 </span>
          <span v-if="detail.isExpired == 0" style="font-weight: bold; color: green"> 否 </span>
        </el-col>
      </el-row>
      <el-row class="mb8">
        <el-col :span="6">
          已存在新增的序列号数量: <span style="font-weight: bold">{{ detail.num }}</span> 个
        </el-col>
      </el-row>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" :disabled="printDisabled" @click="handlePrint()">
            打印
          </el-button>
          <el-button
            type="primary"
            plain
            size="mini"
            v-hasPermi="['distribution:stockCheck:createStockCheckPositionSerial']"
            @click="handleCreateQr">
            新建二维码
          </el-button>
          <el-radio-group v-model="isPage" @change="getList" style="margin: 10px">
            <el-radio label="1">{{ $t('不分页') }}</el-radio>
            <el-radio label="2">{{ $t('分页') }}</el-radio>
          </el-radio-group>
          <el-button
            type="primary"
            plain
            size="mini"
            v-hasPermi="['distribution:stockCheck:setExpiredTime']"
            @click="handleExpireTime({}, 'all')">
            设置全部过期时间
          </el-button>
        </el-col>
      </el-row>
      <!-- 不分页列表 -->
      <v-list
        v-if="isPage == 1"
        @rowSelect="(rows) => (tableNoPageCheck = rows)"
        :list-data="tableNoPageData"
        :prop="[
          { name: $t('序号'), prop: 'indexNo', style: { flex: 1 } },
          { name: $t('序列号'), prop: 'skuSerialId', style: { flex: 1.5 } },
          { name: $t('过期时间'), prop: 'expireTime', style: { flex: 1.5 } },
          {
            name: $t('操作'),
            prop: [
              {
                name: $t('删除'),
                style: 'color:red;',
                permission: ['distribution:stockCheck:deleteStockCheckPositionSerialById'],
                click: (row) => handleDelete(row),
              },
              {
                name: $t('过期时间'),
                permission: ['distribution:stockCheck:setIsExpiredTime'],
                click: (row) => handleExpireTime(row),
              },
            ],
          },
        ]"
        :view-count="20">
      </v-list>
      <div v-if="isPage == 2">
        <el-table @selection-change="(rows) => (tableCheck = rows)" ref="TableRef" :data="tableData">
          <el-table-column align="center" type="selection" width="50" />
          <el-table-column type="index" :label="$t('序号')" width="60" align="center" />
          <el-table-column show-overflow-tooltip :label="$t('序列号')" align="center" prop="skuSerialId" />
          <el-table-column show-overflow-tooltip :label="$t('过期时间')" align="center" prop="expireTime" />
          <el-table-column align="center" fixed="right" :label="$t('操作')">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                style="color: red"
                v-hasPermi="['distribution:stockCheck:deleteStockCheckPositionSerialById']"
                @click="handleDelete(row)">
                {{ $t('删除') }}
              </el-button>
              <el-button
                type="text"
                v-hasPermi="['distribution:stockCheck:setExpiredTime']"
                size="small"
                @click="handleExpireTime(row)">
                {{ $t('过期时间') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">
          <!-- 关闭 -->
          {{ $t('关闭') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 新建二维码 -->
    <el-dialog
      title="新建二维码"
      destroy-on-close
      append-to-body
      :visible.sync="createQrInfo.show"
      width="500px"
      :before-close="() => (createQrInfo.show = false)">
      <el-form
        ref="formRef"
        :model="createQrInfo.form"
        :rules="createQrInfo.rules"
        size="small"
        label-width="50px">
        <el-form-item label="数量" prop="num">
          <el-input-number
            style="width: 200px"
            v-model="createQrInfo.form.num"
            controls-position="right"
            :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCreateQrInfo">
          {{ $t('确认') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 设置过期时间 -->
    <el-dialog
      title="设置过期时间"
      destroy-on-close
      append-to-body
      :visible.sync="expireTime.show"
      width="500px"
      :before-close="() => (expireTime.show = false)">
      <el-form
        ref="expireTimeFormRef"
        :model="expireTime.form"
        :rules="expireTime.rules"
        size="small"
        label-width="80px">
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            v-model="expireTime.form.expireTime"
            type="date"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['distribution:stockCheck:setExpiredTime']" @click="handleSetExpireTime">
          {{ $t('确认') }}
        </el-button>
      </div>
    </el-dialog>
    <QR
      title="详情"
      :dialogVisible="qr.show"
      :addprintNum="4"
      :janCodeList="[5, 6, 7, 8]"
      :barcodeNum="qr.qrData"
      @handleClose="qr.show = false" />
  </div>
</template>

<script>
import {
  getNumInfoByCheckPositionId,
  createStockCheckPositionSerial,
  getStockCheckPositionSerialList,
  getStockCheckPositionSerialListNoPage,
  deleteStockCheckPositionSerialById,
  setExpiredTime,
} from '@/api/distribution/sku/qrPrint'
import VList from '@/components/v-list/index.vue'
import QR from '@/components/QrCode/index.vue'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  components: { VList, QR },
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },

    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      qr: {
        show: false,
        qrData: [],
      },
      tableCheck: [],
      tableNoPageCheck: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      tableNoPageData: [],
      isPage: '1',
      total: 0,
      detail: {},
      createQrInfo: {
        /**显示详情 */
        show: false,
        form: {
          num: 0,
        },
        rules: {
          num: [{ required: true, message: '请选择', trigger: 'blur' }],
        },
      },
      expireTime: {
        /**显示详情 */
        show: false,
        type: '',
        form: {
          expireTime: 0,
        },
        rules: {
          // expireTime: [{ required: true, message: '请选择', trigger: 'blur' }],
        },
      },
    }
  },
  computed: {
    printDisabled() {
      if (this.isPage == '1') {
        return this.tableNoPageCheck.length == 0
      } else {
        return this.tableCheck.length == 0
      }
    },
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.getDetail()
        this.getList()
      }
    },
  },
  methods: {
    handlePrint() {
      this.qr.show = true
      let printData = []
      if (this.isPage == '1') {
        printData = this.tableNoPageCheck.map((i) => i.skuSerialId)
      } else {
        printData = this.tableCheck.map((i) => i.skuSerialId)
      }
      this.qr.qrData = printData.map((i) => {
        return {
          ...i,
          id: i,
          skuNo: '(补)',
        }
      })
    },
    handleDelete(row) {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deleteStockCheckPositionSerialById(row.id).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.getList()
          }
        })
      })
    },
    handleExpireTime(row, type = 'one') {
      this.expireTime.type = type
      this.expireTime.form.expireTime = ''
      this.expireTime.form.skuSerialId = row.skuSerialId
      console.log(`row ==>`, JSON.parse(JSON.stringify(row)))
      console.log(`this.expireTime.form ==>`, JSON.parse(JSON.stringify(this.expireTime.form)))
      this.expireTime.show = true
    },
    handleSetExpireTime() {
      this.$refs['expireTimeFormRef'].validate((valid) => {
        if (valid) {
          let data = {}
          if (this.expireTime.type == 'all') {
            // setAll 是否设置全部过期时间 0-否 1-是
            data = {
              setAll: 1,
              checkPositionId: this.formData.checkPositionId,
              expireTime: this.expireTime.form.expireTime,
            }
          } else {
            data = {
              setAll: 0,
              checkPositionId: this.formData.checkPositionId,
              expireTime: this.expireTime.form.expireTime,
              skuSerialId: this.expireTime.form.skuSerialId,
            }
          }
          console.log(`data ==>`, JSON.parse(JSON.stringify(data)))
          setExpiredTime(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.expireTime.show = false
              this.getList()
            }
          })
        }
      })
    },
    handleCreateQrInfo() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            checkId: this.detail.checkId,
            checkPositionId: this.formData.checkPositionId,
            num: this.createQrInfo.form.num,
          }
          createStockCheckPositionSerial(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.createQrInfo.show = false
              this.getList()
            }
          })
        }
      })
    },
    getDetail() {
      getNumInfoByCheckPositionId({ checkPositionId: this.formData.checkPositionId }).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.detail = { ...res.data }
        }
      })
    },
    getList() {
      this.getDetail()
      if (this.isPage == 1) {
        getStockCheckPositionSerialListNoPage({
          checkPositionId: this.formData.checkPositionId,
        }).then((res) => {
          const { data } = res

          this.tableNoPageData = data.map((item, index) => {
            const { isOutWarehouse, isOnShelf, isBox } = item
            /************************出库情况***********************/
            let isOutWarehouseText, isOutWarehouseStyle
            if (isOutWarehouse == 0) {
              isOutWarehouseText = '未出库'
              isOutWarehouseStyle = { color: 'red' }
            } else if (isOutWarehouse == 1) {
              isOutWarehouseText = '已出库'
              isOutWarehouseStyle = { color: '#13ce66' }
            }
            /************************出库情况 end***********************/

            /************************上架情况***********************/
            let isOnShelfText, isOnShelfStyle
            if (isOnShelf == 0) {
              isOnShelfText = '未上架'
              isOnShelfStyle = { color: 'red' }
            } else if (isOnShelf == 1) {
              isOnShelfText = '已上架'
              isOnShelfStyle = { color: '#13ce66' }
            }
            /************************上架情况 end ***********************/

            /************************装箱情况***********************/
            let isBoxText, isBoxStyle
            // 是否装箱 0-否 1-是
            if (isBox == 0) {
              isBoxText = '否'
              isBoxStyle = { color: 'red' }
            } else if (isBox == 1) {
              isBoxText = '是'
              isBoxStyle = { color: '#13ce66' }
            }
            /**过期时间处理 */
            if (item.isExpired == 0) {
              item.isExpiredTime = '-'
            } else {
              item.isExpiredTime = item.isExpiredTime?.split(' ')[0]
            }
            /************************装箱情况 end ***********************/
            return {
              ...item,
              index,
              indexNo: index + 1,
              idText: item.id,
              isOutWarehouseText,
              isOutWarehouseStyle,
              isOnShelfText,
              isOnShelfStyle,
              isBoxText,
              isBoxStyle,
              check: false,
            }
          })
        })
      } else {
        getStockCheckPositionSerialList({
          ...this.queryParams,
          checkPositionId: this.formData.checkPositionId,
        }).then((res) => {
          const { rows, total } = res
          this.tableData = rows
          this.total = total
        })
      }
    },
    handleCreateQr() {
      this.createQrInfo.form.num = 0
      this.createQrInfo.show = true
    },
    cancel() {
      this.$emit('getList')
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss">
::v-deep .el-table__cell {
  padding: 0;
}
</style>
